import numpy as np
import cv2 as cv

# 创建窗口
win_name = 'HSV Color Picker'
cv.namedWindow(win_name)

# 初始化轨迹条
cv.createTrackbar('H', win_name, 90, 180, lambda _: None)
cv.createTrackbar('S', win_name, 255, 255, lambda _: None)
cv.createTrackbar('V', win_name, 255, 255, lambda _: None)
cv.createTrackbar('OFF/ON', win_name, 0, 1, lambda _: None)

# 创建固定尺寸的黑色图像（用于显示结果）
img = np.zeros((300, 512, 3), dtype=np.uint8)

while True:
    # 获取当前轨迹条值
    h = cv.getTrackbarPos('H', win_name)
    s = cv.getTrackbarPos('S', win_name)
    v = cv.getTrackbarPos('V', win_name)
    switch = cv.getTrackbarPos('OFF/ON', win_name)

    if switch:
        # 高效颜色转换：仅转换单个像素后填充整个图像
        hsv_color = np.array([[[h, s, v]]], dtype=np.uint8)
        bgr_color = cv.cvtColor(hsv_color, cv.COLOR_HSV2BGR)[0, 0]
        img[:] = bgr_color  # 使用广播机制填充整个图像
    else:
        img[:] = 0  # 直接填充黑色

    cv.imshow(win_name, img)

    # 退出机制（ESC键）
    if cv.waitKey(1) == 27:
        break

cv.destroyAllWindows()